package com.xzh.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.xzh.common.utils.HttpUtils;
import com.xzh.common.utils.R;
import com.xzh.gulimall.auth.feign.MemberFeignService;
import com.xzh.common.vo.MemberRespVo;
import com.xzh.gulimall.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/*
* 处理社交登录请求*/
@Slf4j
@Controller
public class OAuth2Controller {
    @Autowired
    private MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/gitee/success")
    public String gitee(@RequestParam("code")String code, HttpSession session) throws Exception {
        System.out.println("run=======");
        Map<String,String> map = new HashMap<>();
        map.put("grant_type","authorization_code");
        map.put("code",code);
        map.put("client_id","05dd4c52cc01aec39b2b53e6369af6b328f91801dd5f05a0b0c3ed5cf637d24f");
        map.put("redirect_uri","http://auth.xzhmall.com/oauth2.0/gitee/success");
        map.put("client_secret","1d0c9d53291f9ffb64cb0a018a1fea27835d9e45239bd40c63ad0b34a99a3fea");

        //1、根据code码换取accessToken
        HttpResponse response = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", new HashMap<>(), map, new HashMap<>());
        //处理
        if(response.getStatusLine().getStatusCode()==200){
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            //知道当前是哪个社交用户
            //如果当前用户是第一次登录网站，--自动注册（为当前社交用户生成会员信息账号，以后这个社交账号对应指定会员）
            //登录或者注册这个社交用户
            Map<String,String> acc = new HashMap<>();
            acc.put("access_token",socialUser.getAccess_token());
            HttpResponse response1 = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", new HashMap<>(), acc);
            if(response1.getStatusLine().getStatusCode()==200){
                String json1 = EntityUtils.toString(response1.getEntity());
                JSONObject jsonObject = JSON.parseObject(json1);
                socialUser.setU_id(jsonObject.getInteger("id"));
                socialUser.setUserName(jsonObject.getString("name"));
            }
            R r = memberFeignService.oauth2login(socialUser);
            //System.out.println(socialUser);
            if(r.getCode()==0){
                MemberRespVo data = r.getData("data", new TypeReference<MemberRespVo>() {
                });
                System.out.println("登录成功，用户信息==="+data);
                //第一次使用session,命令浏览器保存卡号，JSESSIONID这个cookie
                //子域名之间 xzhmall.com  auth.xzhmall.com order.xzhmall.com
                //发卡的时候（指定域名为父域名），即使是子域名系统发的卡，也能使父域名直接使用
                //TODO:1、默认发的令牌。session = dsajkdjl. 作用域，当前域；（解决子域session共享问题)
                //TODO:2、使用JSON的序列化方式来序列化对象数据到redis中
                session.setAttribute("loginUser",data);
                //2、登录成功跳回首页
                return "redirect:http://xzhmall.com";
            }else{
                return "redirect:http://auth.xzhmall.com/login.html";
            }

        }else{
            return "redirect:http://auth.xzhmall.com/login.html";
        }


    }
}
